package com.mc2.docapp.disabilityassessmenttool;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.mc2.docapp.disabilityassessmenttool.Misc.InputFilterMinMax;
import com.mc2.docapp.disabilityassessmenttool.UpperLimb.C_loss_in_10_co_ordinated_activities;
import com.mc2.docapp.disabilityassessmenttool.UpperLimb.CustDataType;

import java.util.HashSet;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

import static com.mc2.docapp.disabilityassessmenttool.utils.Statics.getEditTexts;
import static com.mc2.docapp.disabilityassessmenttool.utils.Statics.router;

public class UpLimbCoActivities extends AppCompatActivity {

    //this is act identifier
    private static final int id = Activities.UPPER_LIMB_CO_ACTIVITIES;

    public C_loss_in_10_co_ordinated_activities c_loss_in_10_co_ordinated_activities = new C_loss_in_10_co_ordinated_activities();

    private EditText writingLeft;
    private EditText writingRight;
    private EditText tyingKnotLeft;
    private EditText tyingKnotRight;
    private EditText buttoningLeft;
    private EditText buttoningRight;
    private EditText drinkingGlassRight;
    private EditText drinkingGlassLeft;
    private EditText ablutionLeft;
    private EditText ablutionRight;
    private EditText puttingshirtLeft;
    private EditText puttingshirtRight;
    private EditText combingLeft;
    private EditText combingRight;
    private EditText eatingLeft;
    private EditText eatingRight;
    private EditText touchingNoseLeft;
    private EditText touchingNoseRight;
    private EditText overheadLiftLeft;
    private EditText overheadLiftRight;

    //db instance
    private Realm realm;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_up_limb_co_activities);
        writingLeft = (EditText) findViewById(R.id.writingLeft);
        writingRight = (EditText) findViewById(R.id.writingRight);
        tyingKnotLeft = (EditText) findViewById(R.id.tyingKnotLeft);
        tyingKnotRight = (EditText) findViewById(R.id.tyingKnotRight);
        buttoningLeft = (EditText) findViewById(R.id.buttoningLeft);
        buttoningRight = (EditText) findViewById(R.id.buttoningRight);
        drinkingGlassRight = (EditText) findViewById(R.id.drinkingGlassRight);
        drinkingGlassLeft = (EditText) findViewById(R.id.drinkingGlassLeft);
        ablutionLeft = (EditText) findViewById(R.id.ablutionLeft);
        ablutionRight = (EditText) findViewById(R.id.ablutionRight);
        puttingshirtLeft = (EditText) findViewById(R.id.puttingshirtLeft);
        puttingshirtRight = (EditText) findViewById(R.id.puttingshirtRight);
        combingLeft = (EditText) findViewById(R.id.combingLeft);
        combingRight = (EditText) findViewById(R.id.combingRight);
        eatingLeft = (EditText) findViewById(R.id.eatingLeft);
        eatingRight = (EditText) findViewById(R.id.eatingRight);
        touchingNoseLeft = (EditText) findViewById(R.id.touchingNoseLeft);
        touchingNoseRight = (EditText) findViewById(R.id.touchingNoseRight);
        overheadLiftLeft = (EditText) findViewById(R.id.overheadLiftLeft);
        overheadLiftRight = (EditText) findViewById(R.id.overheadLiftRight);
        sanitizeInputs();
        initRealmDB();
        loadPrevData();


        Button saveNnextButton = (Button) findViewById(R.id.saveAndNext);
        saveNnextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                c_loss_in_10_co_ordinated_activities.setWriting(new CustDataType(Integer.parseInt(IfNull(writingRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(writingLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.setTyingKnot(new CustDataType(Integer.parseInt(IfNull(tyingKnotRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(tyingKnotLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.setButtoning(new CustDataType(Integer.parseInt(IfNull(buttoningRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(buttoningLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.setDrinkingFromGlass(new CustDataType(Integer.parseInt(IfNull(drinkingGlassRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(drinkingGlassLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.setAblution(new CustDataType(Integer.parseInt(IfNull(ablutionRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(ablutionLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.setPuttingShirt(new CustDataType(Integer.parseInt(IfNull(puttingshirtRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(puttingshirtLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.setCombing(new CustDataType(Integer.parseInt(IfNull(combingRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(combingLeft.getText().toString(), "0")), 0d, 0, 0));


                c_loss_in_10_co_ordinated_activities.setEating(new CustDataType(Integer.parseInt(IfNull(eatingRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(eatingLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.setTouchingNose(new CustDataType(Integer.parseInt(IfNull(touchingNoseRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(touchingNoseLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.setOverheadLifting(new CustDataType(Integer.parseInt(IfNull(overheadLiftRight.getText().toString(), "0")),
                        Integer.parseInt(IfNull(overheadLiftLeft.getText().toString(), "0")), 0d, 0, 0));

                c_loss_in_10_co_ordinated_activities.calc(c_loss_in_10_co_ordinated_activities);

                try {
//                    System.out.println(new ObjectMapper().writeValueAsString(c_active_rom));
                } catch (Exception e) {
                }
                System.out.println();
                c_loss_in_10_co_ordinated_activities.setId(id);

                NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().setLoss_in_10_co_ordinated_activities(c_loss_in_10_co_ordinated_activities);
                calTotalArmComponent(true);
                calTotalArmComponent(false);
                realm.beginTransaction();
                realm.deleteAll();
                realm.insert(c_loss_in_10_co_ordinated_activities);
                realm.commitTransaction();

                Intent intent = new Intent(UpLimbCoActivities.this, router(UpLimbCoActivities.class));
                startActivity(intent);
            }
        });
        Button clearAll = (Button) findViewById(R.id.clear);
        clearAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashSet<EditText> views = new HashSet<>();
                getEditTexts((ViewGroup) findViewById(R.id.activity_main), views);
                for (EditText h : views)
                    h.setText("");
            }
        });


    }

    private double calByFormula(double a, double b) {
        if(a<b){
            a = a + b;
            b = a - b;
            a = a - b;
        }
        double c = a + (((90 - a) * b) / 90.0);
        return c;
    }

    private void calTotalArmComponent(Boolean isLeft) {
        if(isLeft) {
            double  acRomSUmLeft = NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().getActive_rom_degrees().getInnerCalculations().getSummation_left();
            double musPowerSumLeft = NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().getMuscle_power().getInnerCalculations().getSummation_left();
            double coActLeft = NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().getLoss_in_10_co_ordinated_activities().getInner_calculations().getSummation_left();

            double step1;
            double step2;
            double step3;

            step1 = calByFormula(acRomSUmLeft,musPowerSumLeft);
            step2 = calByFormula(step1,coActLeft);
            if(step2 > 90d) {
              step2 = 90d;
            }
            NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().setTotalArmCommponentLeft(step2);

        } else {

            double  acRomSUmRight = NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().getActive_rom_degrees().getInnerCalculations().getSummation_right();
            double musPowerSumRight = NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().getMuscle_power().getInnerCalculations().getSummation_right();
            double coActRight = NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().getLoss_in_10_co_ordinated_activities().getInner_calculations().getSummation_right();

            double step1;
            double step2;
            double step3;

            step1 = calByFormula(acRomSUmRight,musPowerSumRight);
            step2 = calByFormula(step1,coActRight);
            if(step2 > 90d) {
                step2 = 90d;
            }
            NewPatient.finalDto.getClass_upperLimb_component().getClass_arm_component().setTotalArmCommponentRight(step2);
        }
    }

    private void mapUI(C_loss_in_10_co_ordinated_activities oldData) {
        writingLeft.setText(String.valueOf((long) (oldData.getWriting().getActual_left())));
        writingRight.setText(String.valueOf((long) (oldData.getWriting()).getActual_right()));

        tyingKnotLeft.setText(String.valueOf((long) (oldData.getTyingKnot().getActual_left())));
        tyingKnotRight.setText(String.valueOf((long) (oldData.getTyingKnot().getActual_right())));

        buttoningLeft.setText(String.valueOf((long) (oldData.getButtoning().getActual_left())));
        buttoningRight.setText(String.valueOf((long) (oldData.getButtoning().getActual_right())));

        drinkingGlassLeft.setText(String.valueOf((long) (oldData.getDrinkingFromGlass().getActual_left())));
        drinkingGlassRight.setText(String.valueOf((long) (oldData.getDrinkingFromGlass().getActual_right())));

        ablutionLeft.setText(String.valueOf((long) (oldData.getAblution().getActual_left())));
        ablutionRight.setText(String.valueOf((long) (oldData.getAblution().getActual_right())));

        puttingshirtLeft.setText(String.valueOf((long) (oldData.getPuttingShirt().getActual_left())));
        puttingshirtRight.setText(String.valueOf((long) (oldData.getPuttingShirt().getActual_right())));

        combingLeft.setText(String.valueOf((long) (oldData.getCombing().getActual_left())));
        combingRight.setText(String.valueOf((long) (oldData.getCombing().getActual_right())));

        eatingLeft.setText(String.valueOf((long) (oldData.getEating().getActual_left())));
        eatingRight.setText(String.valueOf((long) (oldData.getEating().getActual_right())));

        touchingNoseLeft.setText(String.valueOf((long) (oldData.getTouchingNose().getActual_left())));
        touchingNoseRight.setText(String.valueOf((long) (oldData.getTouchingNose().getActual_right())));

        overheadLiftLeft.setText(String.valueOf((long) (oldData.getOverheadLifting().getActual_left())));
        overheadLiftRight.setText(String.valueOf((long) (oldData.getOverheadLifting().getActual_right())));

    }


    public void sanitizeInputs() {
        writingLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        writingRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        tyingKnotLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        tyingKnotRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        buttoningLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        buttoningRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        drinkingGlassRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        drinkingGlassLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        ablutionLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        ablutionRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        puttingshirtLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        puttingshirtRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        combingLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        combingRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        eatingLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        eatingRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        touchingNoseLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        touchingNoseRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        overheadLiftLeft.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
        overheadLiftRight.setFilters(new InputFilter[]{new InputFilterMinMax("0", "9")});
    }

    public String IfNull(String value, String defaultValue) {
        if (value == null || value.isEmpty()) {
            return defaultValue;
        } else {
            return value;
        }
    }

    private void initRealmDB() {
        Realm.init(getApplicationContext());
        // realm = Realm.getDefaultInstance();
        RealmConfiguration config = new RealmConfiguration.Builder().name(id+".realm").build();
        realm = Realm.getInstance(config);
    }

    private void loadPrevData() {
        final RealmResults<C_loss_in_10_co_ordinated_activities> dtos = realm.where(C_loss_in_10_co_ordinated_activities.class).findAll();
//        .equalTo("id",id).findAll();
        System.out.println();
        try {
            //apply ui
            //
            //mapUI(new C_loss_in_10_co_ordinated_activities().strip(dtos.get(0)));
            //
            //realm.beginTransaction();
            //dtos.get(0).deleteFromRealm();
            //realm.commitTransaction();
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
            //no prev data found
        }
    }

}
